package com.edu.servlet;

import com.edu.bean.User;
import com.edu.dao.UserDao;
import com.edu.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/login")
public class UserLoginServlet extends HttpServlet {
    private UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 如果已经登录，直接跳转到首页
        if (request.getSession().getAttribute("user") != null) {
            response.sendRedirect(request.getContextPath() + "/user/home");
            return;
        }
        request.getRequestDispatcher("/user/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 参数验证
        if (username == null || password == null ||
                username.trim().isEmpty() || password.trim().isEmpty()) {
            request.setAttribute("error", "用户名和密码不能为空");
            request.getRequestDispatcher("/user/login.jsp").forward(request, response);
            return;
        }

        // 密码MD5加密
        password = MD5Util.md5(password);

        // 验证用户名密码
        User user = userDao.findByUsernameAndPassword(username, password,2);

        if (user != null) {
            // 登录成功
            request.getSession().setAttribute("user", user);
            response.sendRedirect(request.getContextPath() + "/user/home");
        } else {
            // 登录失败
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("/user/login.jsp").forward(request, response);
        }
    }
}